﻿using Sprout.Schedule.Consts;
using Sprout.Schedule.Dtos;
using Sprout.Core.Utils;
using Quartz;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Sprout.Core.Extensions;
using Sprout.Schedule.Enums;

namespace Sprout.Schedule.Jobs
{
    /// <summary>
    /// 调用API任务的实现
    /// </summary>
    public class ApiJob : JobBase, IJob
    {
        /// <summary>
        /// 任务开始
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task Execute(IJobExecutionContext context)
        {
            //设置TaskId
            TaskId = context.JobDetail.JobDataMap.GetLong(JobConst.Task_ID_KEY);

            //此处不需要等待
            Execute();

            return Task.CompletedTask;
        }

        /// <summary>
        /// 业务逻辑执行，调用API
        /// </summary>
        /// <returns></returns>
        public async void Execute()
        {
            //如果任务正在运行中
            if (await IsRuning())
            {
                return;
            }
            //开始任务
            await JobRunAsync();

            var taskInfo = await GetTaskInfoAsync();
            ApiJobParamsDto dto = new ApiJobParamsDto()
            {
                TaskId = TaskId
            };
            try
            {
                await HttpHelper.PostAsJsonAsync(taskInfo.JobFullName, dto);
            }
            catch (Exception e)
            {
                /**
                 * 如果报异常
                 * Could not load file or assembly 'System.Net.Http.Formatting, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. 系统找不到指定的文件。
                 * NUGET引用  Microsoft.AspNet.WebApi.Client
                 */
                await LogAsync($"调用任务异常:{e.Message}", e);
            }
        }


        /// <summary>
        /// 是否正在执行
        /// </summary>
        /// <returns></returns>
        public async Task<bool> IsRuning()
        {
            var task = await GetTaskInfoAsync();
            if (task.RunStatus == TaskRunStatusEnum.Running)
            {
                //如果上次运行时间超过设置的运行超时时间
                if (task.RunTimeoutSeconds > 0 && (DateTime.Now - task.RunTime.Value).TotalSeconds > task.RunTimeoutSeconds)
                {
                    await LogAsync("任务超过最长超时时间，强制结束");
                    //任务完成
                    await JobRunEndAsync();
                    return false;
                }
                else
                {
                    return true;
                }
            }
            return false;
        }
    }
}
